package com.stn.zjx.givingtreasure.fragment.main;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allenliu.badgeview.BadgeFactory;
import com.allenliu.badgeview.BadgeView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.activity.address.AddressManagerActivity;
import com.stn.zjx.givingtreasure.activity.bi.BiMainActivity;
import com.stn.zjx.givingtreasure.activity.bi.CreateEthWalletActivity;
import com.stn.zjx.givingtreasure.activity.bi.FirstCreateEthBackUpActivity;
import com.stn.zjx.givingtreasure.activity.bi.FirstCreateWhatBlockActivity;
import com.stn.zjx.givingtreasure.activity.dynamic.ReleaseDynamicActivity;
import com.stn.zjx.givingtreasure.activity.msg.MsgTypeListActivity;
import com.stn.zjx.givingtreasure.activity.set.UserSetActivity;
import com.stn.zjx.givingtreasure.activity.userprofile.ModifyUserProfileActivity;
import com.stn.zjx.givingtreasure.activity.userwallet.UserWalletActivity;
import com.stn.zjx.givingtreasure.domain.UserProfileDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.base.BaseMainFragment;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.MsgNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.service.WalletUserService;
import com.stn.zjx.givingtreasure.table.User;
import com.vondear.rxtools.RxActivityTool;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import de.hdodenhof.circleimageview.CircleImageView;

@SuppressWarnings("ALL")
public class MainMyFragment extends BaseMainFragment {
    public View rootView;
    @BindView(R.id.avatar_civ)
    CircleImageView avatarCiv;
    @BindView(R.id.nick_name)
    TextView nickName;
    @BindView(R.id.msg_iv)
    ImageView msgIv;
    @BindView(R.id.msg_rl)
    RelativeLayout msgRl;
    @BindView(R.id.set_iv)
    ImageView setIv;
    @BindView(R.id.set_bt)
    RelativeLayout setBt;
    @BindView(R.id.twinklingRefresh)
    TwinklingRefreshLayout twinklingRefresh;

    @BindView(R.id.login_register_tv)
    TextView loginRegisterTv;
    @BindView(R.id.pre_pay_iv)
    ImageView prePayIv;
    @BindView(R.id.pre_pay_rl)
    RelativeLayout prePayRl;
    @BindView(R.id.pre_pay_num)
    TextView prePayNum;
    @BindView(R.id.pre_receipt_iv)
    ImageView preReceiptIv;
    @BindView(R.id.pre_receipt_rl)
    RelativeLayout preReceiptRl;
    @BindView(R.id.pre_receipt_num)
    TextView preReceiptNum;
    @BindView(R.id.pre_evaluate_iv)
    ImageView preEvaluateIv;
    @BindView(R.id.pre_evaluate_rl)
    RelativeLayout preEvaluateRl;
    @BindView(R.id.pre_evaluate_num)
    TextView preEvaluateNum;
    @BindView(R.id.after_sale_iv)
    ImageView afterSaleIv;
    @BindView(R.id.after_sale_rl)
    RelativeLayout afterSaleRl;
    @BindView(R.id.after_sale_num)
    TextView afterSaleNum;
    @BindView(R.id.myself_order_iv)
    ImageView myselfOrderIv;
    @BindView(R.id.myself_order_rl)
    RelativeLayout myselfOrderRl;
    @BindView(R.id.myself_order_num)
    TextView myselfOrderNum;
    @BindView(R.id.already_reserved_num)
    TextView alreadyReservedNum;
    @BindView(R.id.already_reserved_bt)
    RelativeLayout alreadyReservedBt;
    @BindView(R.id.take_free_num)
    TextView takeFreeNum;
    @BindView(R.id.take_free_bt)
    RelativeLayout takeFreeBt;
    @BindView(R.id.user_attention_num)
    TextView userAttentionNum;
    @BindView(R.id.store_attention)
    TextView storeAttention;
    @BindView(R.id.shop_attention)
    TextView shopAttention;
    @BindView(R.id.like_dynamics)
    TextView likeDynamics;
    @BindView(R.id.my_wallet_iv)
    ImageView myWalletIv;
    @BindView(R.id.my_shop_iv)
    ImageView myShopIv;

    @BindView(R.id.want_job_iv)
    ImageView wantJobIv;
    @BindView(R.id.my_history_iv)
    ImageView myHistoryIv;
    @BindView(R.id.go_dynamic_iv)
    ImageView goDynamicIv;
    @BindView(R.id.private_activity_iv)
    ImageView privateActivityIv;
    @BindView(R.id.my_imgs_iv)
    ImageView myImgsIv;
    @BindView(R.id.my_videos_iv)
    ImageView myVideosIv;
    @BindView(R.id.default_nickname_rl)
    RelativeLayout defaultNicknameRl;

    @BindView(R.id.use_type_tv)
    TextView useTypeTv;

    @BindView(R.id.rank_num_tv)
    RelativeLayout rankNumTv;
    @BindView(R.id.rank_num_tv1)
    TextView rankNumTv1;
    @BindView(R.id.rank_num_tv2)
    TextView rankNumTv2;


    BadgeView badgeView;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container) {
        if (rootView == null) {
            rootView = View.inflate(activity, R.layout.fragment_main_my, null);
            ButterKnife.bind(this, rootView);
        }
        return rootView;
    }

    @Override
    public void initData() {
        badgeView=BadgeFactory.create(activity)
                .setTextColor(getResources().getColor(R.color.white))
                .setWidthAndHeight(20,20)
                .setBadgeBackground(getResources().getColor(R.color.red))
                .setTextSize(10)
                .setBadgeGravity(Gravity.RIGHT|Gravity.TOP)
                .setBadgeCount("0")
                .setShape(BadgeView.SHAPE_CIRCLE)
                .bind(msgRl);
        badgeView.setVisibility(View.GONE);
        badgeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                RxActivityTool.skipActivity(activity, MsgTypeListActivity.class);
            }
        });

        ProgressLayout headerView = new ProgressLayout(activity);
        headerView.setColorSchemeResources(R.color.colorAccent);
        twinklingRefresh.setHeaderView(headerView);
        twinklingRefresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                initUser();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {

            }
        });
        twinklingRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                twinklingRefresh.setEnableRefresh(true);
                initUser();
            }
        }, 200);
    }


    @OnClick({R.id.avatar_civ, R.id.nick_name, R.id.msg_iv,R.id.msg_rl,
            R.id.set_bt,R.id.default_nickname_rl,
      R.id.go_block_chain,
    R.id.release_dynamic,
    R.id.go_wallet_bt

    })
    public void onViewClicked(View view) {


        switch (view.getId()) {
            case R.id.default_nickname_rl:
                RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                break;
            case R.id.avatar_civ:
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                RxActivityTool.skipActivity(activity,ModifyUserProfileActivity.class);
                break;
            case R.id.nick_name:
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                RxActivityTool.skipActivity(activity,ModifyUserProfileActivity.class);
                break;
            case R.id.msg_iv:
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                RxActivityTool.skipActivity(activity, MsgTypeListActivity.class);
                break;
            case R.id.msg_rl:
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                 RxActivityTool.skipActivity(activity, MsgTypeListActivity.class);
                break;
            case R.id.set_bt:
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                RxActivityTool.skipActivity(activity, UserSetActivity.class);
                break;
            case R.id.go_block_chain:
                if(WalletUserService.getInstance(getContext()).getAddressCount()>0){
                    RxActivityTool.skipActivity(activity,BiMainActivity.class);
                }else{
                    RxActivityTool.skipActivity(activity,FirstCreateWhatBlockActivity.class);
                }

                break;
                case R.id.release_dynamic:
                RxActivityTool.skipActivity(activity, ReleaseDynamicActivity.class);
                break;
            case R.id.go_wallet_bt:
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                RxActivityTool.skipActivity(activity,UserWalletActivity.class);
                break;

        }
    }


    public void initDefault() {
        nickName.setVisibility(View.GONE);
        useTypeTv.setVisibility(View.GONE);
        badgeView.setVisibility(View.GONE);
        rankNumTv.setVisibility(View.GONE);
        rankNumTv1.setText("" + getString(R.string.growthvalue));
        rankNumTv2.setText("" + getString(R.string.growthvalue));
        Glide.with(this)
                .asBitmap()
                .load(R.mipmap.default_avatar)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        avatarCiv.setImageBitmap(resource);
                    }
                });

        defaultNicknameRl.setVisibility(View.VISIBLE);
    }

    public void initLocationUser() {
        User userOnline = UserService.getInstance(activity).getOnlineLoginUser();
         if(userOnline==null){
             return;
         }
        defaultNicknameRl.setVisibility(View.GONE);
        nickName.setVisibility(View.VISIBLE);
        useTypeTv.setVisibility(View.VISIBLE);
        rankNumTv.setVisibility(View.VISIBLE);


        Glide.with(this)
                .asBitmap()
                .thumbnail(0.2f)
                .load(String.valueOf(userOnline.getUserAvatar())).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                avatarCiv.setImageBitmap(resource);
            }
            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                avatarCiv.setImageResource(R.mipmap.default_avatar);
            }

            @Override
            public void onLoadStarted(@Nullable Drawable placeholder) {
                super.onLoadStarted(placeholder);
                avatarCiv.setImageResource(R.mipmap.default_avatar);
            }
        });

        nickName.setText(userOnline.getUserNickname());

        rankNumTv1.setText("" + getString(R.string.growthvalue) + " " + userOnline.getUserRankeneray());
        rankNumTv2.setText("" + getString(R.string.growthvalue) + " " + userOnline.getUserRankeneray());
    }


    public void initUser() {
        if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
            initDefault();
            return;
        }
        User userOnline = UserService.getInstance(activity).getOnlineLoginUser();
        UserNetImpl.user_getuserprofile_bytoken(userOnline.getToken(),userOnline.getUserId()+"user_getuserprofile_bytoken",
                new StringCallback() {
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        twinklingRefresh.finishRefreshing();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful()&&!activity.isFinishing()) {
                            user_getuserprofile_bytoken(response.body());
                        }
                    }
                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (response.isSuccessful()&&!activity.isFinishing()) {
                            user_getuserprofile_bytoken(response.body());
                        }
                    }
                });

        MsgNetImpl
                .query_get_no_read_all_msg(userOnline.getToken(),userOnline.getUserId()+ "_query_get_no_read_all_msg",
                        new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful()&&!activity.isFinishing()) {
                                    query_get_no_read_all_msg(response.body());
                                }

                            }

                            @Override
                            public void onCacheSuccess(Response<String> response) {
                                super.onCacheSuccess(response);
                                if (response.isSuccessful()&&!activity.isFinishing()) {
                                    query_get_no_read_all_msg(response.body());
                                }
                            }
                        });



    }

    @Override
    public void onStart() {
        super.onStart();
        initUser();
    }
    //成功登录
    private void loginSuccess(UserProfileDomain domain) {
        boolean isLogin= UserService.getInstance(activity)
                .login(domain.getData());
          if(!isLogin){
              boolean isExitLogin= UserService.getInstance(activity)
                      .exitLogin();
              if(isExitLogin){
                  initDefault();
              }
          }
    }




    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
             if(isVisibleToUser){
                 if(rootView!=null){
                     initUser();
                 }
             }
    }

    //处理，通过token获取用户个人资料后的操作
    public void user_getuserprofile_bytoken(String result){
         if(result==null||result.length()==0){
             return;
         }
        Gson gson=new Gson();
        UserProfileDomain domain=gson.fromJson(result.trim(), UserProfileDomain.class);
        switch (domain.getStatus()){
            case BaseApi.REQUEST_SUCCESS_CODE:
                loginSuccess(domain);
                initLocationUser();
                break;
            case BaseApi.REQUEST_LOGINEXIT_ERROR_CODE:
                activity.showToast(domain.getMessage());
                boolean isExitLogin= UserService.getInstance(activity)
                        .exitLogin();
                if(isExitLogin){
                    initDefault();
                }
                break;
            case BaseApi.REQUEST_TOKEN_ERROR_CODE:
                boolean isExit= UserService.getInstance(activity)
                        .exitLogin();
                if(isExit){
                    initDefault();
                }
                break;
        }
    }
    //获取未读消息
    public void query_get_no_read_all_msg(String data){
        if(data==null||data.length()==0){
            return;
        }
        try {
            JSONObject result=new JSONObject(data);
            switch (result.getInt(BaseApi.KEY_STATUS)){
                case BaseApi.REQUEST_SUCCESS_CODE:
                    int  msg_count=result.getInt("data");
                    if(msg_count==0){
                        badgeView.setVisibility(View.GONE);
                    }else{
                        if(msg_count>=99){
                            badgeView.setBadgeCount("99+");
                        }else{
                            badgeView.setBadgeCount(""+msg_count);
                        }
                        badgeView.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
